const http = require('http')
const fs = require('fs')
const path = require('path')
const mines = {
    html:'text/html',
    css:'text/css',
    js:'text/javascript',
    png:'image/png',
    jpg:'image/jpg',
    gif:'image/gif',
    mp4:'video/mp4',
    mp3:'audio/mpeg',
    json:'application/json'
}

const server = http.createServer((request,response)=>{

    // 判断是否是get请求 这里因为是访问静态资源 所以判断get 
    if(request.method !== "GET"){
        response.statusCode = 405;
        response.end('<h1>405 Method Not Allowed</h1>')
        return;
    }

    const {pathname} = new URL(request.url,'http://127.0.0.1:9000')

    const rootPath = __dirname + '/status' //配置网站根目录（静态资源目录）

    let statusPath = rootPath + pathname

    fs.readFile(statusPath,(err,data)=>{
        // 错误信息处理
        if(err){
            console.log(err.code);
            switch(err.code){
                // 资源未找到
                case 'ENOENT': 
                    //enoent
                    response.statusCode = 404;
                    response.end('<h1>404 Not Found</h1>');
                    break;
                // 访问权限不够
                case 'EPERM': 
                    //eperm 
                    response.statusCode = 403;
                    response.end('<h1>403 Forbidden</h1>');
                    break;
                // 其他错误 这里统一归为服务器错误
                default: 
                    response.statusCode = 500;
                    response.end('<h1>Server Erroe</h1>')
            }

            return;
        }
        
        let ext = path.extname(statusPath).slice(1)

        if(ext){
            // charset=utf-8 用于解决乱码问题 注意：响应头字符集格式优先级永远最高
            if(ext==='html'){
                response.setHeader('content-type',mines[ext]+";charset=utf-8")
            }else{
                response.setHeader('content-type',mines[ext])
            }
        }else{
            response.setHeader('content-type','application/octet-stream')
        }


        response.end(data)
    })
})

server.listen(9000,()=>{
    console.log('node服务启动');
})


